package com.zbkj.common.function;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorBigInt;
import com.googlecode.aviator.runtime.type.AviatorJavaType;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.Set;

public class ListsumFunction extends AbstractFunction {

    @Override
    public String getName() {
        return "listsum";
    }



    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
        String name1 = ((AviatorJavaType) arg1).getName();
        Set<String> strings = env.keySet();
        Integer count = 0;
        for (String string : strings) {
            if(string.startsWith(name1)){
                count += 1;
            }
        }
        double sum = 0;
        for (Integer i = 0; i < count; i++) {
            Number o1 = (Number)env.get(name1 + i);
            sum += o1.doubleValue();
        }

        return new AviatorBigInt(BigDecimal.valueOf(sum).setScale(2, RoundingMode.HALF_UP).doubleValue());
    }

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        String name1 = ((AviatorJavaType) arg1).getName();
        String name2 = ((AviatorJavaType) arg2).getName();
        Set<String> strings = env.keySet();
        Integer count = 0;
        for (String string : strings) {
            if(string.startsWith(name1)){
                count += 1;
            }
        }
        double sum = 0;
        for (Integer i = 0; i < count; i++) {
            Number o1 = (Number)env.get(name1 + i);
            Number o2 = (Number)env.get(name2 + i);
            sum += o1.doubleValue() * o2.doubleValue();
        }
        return new AviatorBigInt(BigDecimal.valueOf(sum).setScale(2, RoundingMode.HALF_UP).doubleValue());
    }

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {
        String name1 = ((AviatorJavaType) arg1).getName();
        String name2 = ((AviatorJavaType) arg2).getName();
        String name3 = ((AviatorJavaType) arg3).getName();
        Set<String> strings = env.keySet();
        Integer count = 0;
        for (String string : strings) {
            if(string.startsWith(name1)){
                count += 1;
            }
        }
        double sum = 0;
        for (Integer i = 0; i < count; i++) {
            Number o1 = Double.valueOf(env.get(name1 + i).toString());
            Number o2 = Double.valueOf(env.get(name2 + i).toString());
            Number o3 = Double.valueOf(env.get(name3 + i).toString());
            sum += o1.doubleValue() * o2.doubleValue() * o3.doubleValue();
        }
        return new AviatorBigInt(BigDecimal.valueOf(sum).setScale(2, RoundingMode.HALF_UP).doubleValue());
    }
}
